package com.cskaoyan.market.service.wx.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.wx.WxOrderService;
import com.cskaoyan.market.util.MarketConstant;
import com.cskaoyan.market.util.wx.HandleOptionUtil;
import com.cskaoyan.market.vo.wx.lhh.HandleOptionVo;
import com.cskaoyan.market.vo.wx.lhh.OrderInfoVo;
import com.cskaoyan.market.vo.wx.lhh.WxGoodsVo;
import com.cskaoyan.market.vo.wx.lhh.WxOrderVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @ClassName WxOrderServiceImpl
 * @Description
 * @Author MZ
 * @Date 2023/5/19 21:41
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;

    @Override
    public List<WxOrderVo> orderList(List<Short> orderStatusList, Integer page, Integer limit) {
        // 根据orderStatus查询order表，获取
        MarketOrderExample orderExample = new MarketOrderExample();
        orderExample.or().andDeletedEqualTo(false).andOrderStatusIn(orderStatusList);
        // 查询订单列表
        PageHelper.startPage(page, limit);
        List<MarketOrder> marketOrders = orderMapper.selectByExampleSelective(orderExample, MarketOrder.Column.orderSn, MarketOrder.Column.orderStatus, MarketOrder.Column.aftersaleStatus, MarketOrder.Column.actualPrice, MarketOrder.Column.id);

        List<WxOrderVo> wxOrderVos = new ArrayList<>();

        for (MarketOrder marketOrder : marketOrders) {
            WxOrderVo orderVo = new WxOrderVo();
            // 订单状态码
            Short orderStatus = marketOrder.getOrderStatus();
            // 转换为转态文本
            orderVo.setOrderStatusText(HandleOptionUtil.convertStatusText(orderStatus));
            orderVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            orderVo.setIsGroupin(false);
            orderVo.setOrderSn(marketOrder.getOrderSn());
            orderVo.setActualPrice(marketOrder.getActualPrice());
            orderVo.setId(marketOrder.getId());

            // goodsList 根据orderId查询商品
            MarketOrderGoodsExample goodsExample = new MarketOrderGoodsExample();
            goodsExample.or().andDeletedEqualTo(false).andOrderIdEqualTo(marketOrder.getId());
            // 获取对应订单的商品列表
            List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExampleSelective(goodsExample, MarketOrderGoods.Column.goodsName, MarketOrderGoods.Column.picUrl, MarketOrderGoods.Column.price, MarketOrderGoods.Column.id, MarketOrderGoods.Column.goodsName, MarketOrderGoods.Column.specifications, MarketOrderGoods.Column.number);
            List<WxGoodsVo> goodsVos = new ArrayList<>();

            for (MarketOrderGoods orderGoods : orderGoodsList) {
                WxGoodsVo goodsVo = new WxGoodsVo();
                goodsVo.setNumber(orderGoods.getNumber());
                goodsVo.setPicUrl(orderGoods.getPicUrl());
                goodsVo.setPrice(orderGoods.getPrice());
                goodsVo.setId(orderGoods.getId());
                goodsVo.setGoodsName(orderGoods.getGoodsName());
                goodsVo.setSpecifications(orderGoods.getSpecifications());
                goodsVos.add(goodsVo);
            }
            orderVo.setGoodsList(goodsVos);
            // handleOption TODO 添加判断状态的逻辑
            HandleOptionVo handleOption = HandleOptionUtil.getHandleOption(orderStatus);
            orderVo.setHandleOption(handleOption);
            // 添加到list
            wxOrderVos.add(orderVo);
        }
        return wxOrderVos;
    }

    @Override
    public OrderInfoVo getOrderInfo(Integer orderId) {

        MarketOrderExample orderExample = new MarketOrderExample();
        orderExample.or().andDeletedEqualTo(false).andIdEqualTo(orderId);
        MarketOrder order = orderMapper.selectOneByExample(orderExample);
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setConsignee(order.getConsignee());
        orderInfoVo.setAddress(order.getAddress());
        orderInfoVo.setAddTime(order.getAddTime());
        orderInfoVo.setOrderSn(order.getOrderSn());
        orderInfoVo.setActualPrice(order.getActualPrice());
        orderInfoVo.setMobile(order.getMobile());
        orderInfoVo.setMessage(order.getMessage());
        // 获取状态
        Short orderStatus = order.getOrderStatus();
        orderInfoVo.setOrderStatusText(HandleOptionUtil.convertStatusText(orderStatus));
        orderInfoVo.setAftersaleStatus(order.getAftersaleStatus());
        orderInfoVo.setGoodsPrice(order.getGoodsPrice());
        orderInfoVo.setCouponPrice(order.getCouponPrice());
        orderInfoVo.setId(order.getId());
        orderInfoVo.setFreightPrice(order.getFreightPrice());
        orderInfoVo.setHandleOption(HandleOptionUtil.getHandleOption(orderStatus));

        return orderInfoVo;
    }

    @Override
    public List<MarketOrderGoods> getOrderGoodsList(Integer orderId) {

        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.or().andDeletedEqualTo(false).andOrderIdEqualTo(orderId);

        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        return orderGoods;
    }


    @Override
    public int cancelOrderByOrderId(Integer orderId) {
        /*
            取消订单
            修改订单状态，从未付款修改为用户取消
        */

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus(MarketConstant.USER_CANCEL);
        marketOrder.setUpdateTime(LocalDateTime.now());

        int row = orderMapper.updateByPrimaryKeySelective(marketOrder);


        return row;
    }

    @Override
    public int refundOrderByOrderId(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus(MarketConstant.APPLY_REFUND);
        marketOrder.setUpdateTime(LocalDateTime.now());

        int row = orderMapper.updateByPrimaryKeySelective(marketOrder);

        return row;
    }

    @Override
    public int deleteOrderByOrderId(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(LocalDateTime.now());

        int row = orderMapper.updateByPrimaryKeySelective(marketOrder);

        return row;
    }


    @Override
    public int confirmOrderByOrderId(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus(MarketConstant.USER_RECEIPT);
        marketOrder.setUpdateTime(LocalDateTime.now());

        int row = orderMapper.updateByPrimaryKeySelective(marketOrder);

        return row;
    }

    @Transactional
    @Override
    public int commentOrderGoods(Integer orderGoodsId, String content, Short star, Boolean hasPicture, String[] picUrls, Integer userId) {
        // 先查询出goodsId
        MarketOrderGoodsExample goodsExample = new MarketOrderGoodsExample();
        goodsExample.or().andDeletedEqualTo(false).andIdEqualTo(orderGoodsId);
        MarketOrderGoods marketOrderGoods = orderGoodsMapper.selectOneByExample(goodsExample);
        Integer goodsId = marketOrderGoods.getGoodsId();

        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(goodsId);
        marketComment.setContent(content);
        marketComment.setStar(star);
        marketComment.setHasPicture(hasPicture);
        marketComment.setPicUrls(picUrls);
        marketComment.setDeleted(false);
        marketComment.setAddTime(LocalDateTime.now());
        marketComment.setUpdateTime(LocalDateTime.now());

        marketComment.setUserId(userId);
        int row1 = commentMapper.insertSelective(marketComment);

        Integer commentId = marketComment.getId();
        marketOrderGoods.setComment(commentId);
        marketOrderGoods.setUpdateTime(LocalDateTime.now());
        int row2 = orderGoodsMapper.updateByPrimaryKeySelective(marketOrderGoods);

        if (row1 != row2) {
            return 0;
        }
        return 1;
    }

    @Override
    public MarketOrderGoods getOrderGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample goodsExample = new MarketOrderGoodsExample();
        goodsExample.or().andDeletedEqualTo(false).andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        MarketOrderGoods orderGoods = orderGoodsMapper.selectOneByExample(goodsExample);

        return orderGoods;
    }

    // 返回添加成功之后的orderId
    @Transactional
    @Override
    public Integer submitOrder(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, String message, Integer grouponRulesId, Integer grouponLinkId, Integer userId) {
        // 获得用户信息
        MarketUser user = userMapper.selectByPrimaryKey(userId);
        MarketAddress address = addressMapper.selectByPrimaryKey(addressId);
        MarketCartExample marketCartEx = new MarketCartExample();
        marketCartEx.or().andDeletedEqualTo(false).andCheckedEqualTo(true);
        List<MarketCart> cartList = cartMapper.selectByExample(marketCartEx);
        MarketCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
        MarketGrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);

        MarketOrder order = new MarketOrder();
        order.setUserId(userId);
        String orderSn = getOrderSn();
        order.setOrderSn(orderSn);
        order.setOrderStatus(MarketConstant.NO_PAYMENT);
        order.setAftersaleStatus((short) 0);
        order.setConsignee(address.getName());
        String addressDet = address.getProvince() + address.getCity() + " " + address.getAddressDetail();
        order.setAddress(addressDet);
        order.setMobile(address.getTel());
        order.setMessage(message);
        BigDecimal goodsPrice = new BigDecimal(0);
        for (MarketCart cart : cartList) {
            Short number = cart.getNumber();
            goodsPrice = goodsPrice.add(cart.getPrice()).multiply(BigDecimal.valueOf(number));
        }
        order.setGoodsPrice(goodsPrice);
        // 运费
        BigDecimal freightPrice = new BigDecimal(10);
        order.setFreightPrice(freightPrice);

        BigDecimal couponPrice = new BigDecimal(0);
        if (coupon != null) {
            couponPrice = coupon.getDiscount();
        }
        order.setCouponPrice(couponPrice);
        BigDecimal integralPrice = new BigDecimal(0);
        order.setIntegralPrice(integralPrice);
        if (grouponRules == null ){
            order.setGrouponPrice(new BigDecimal(0));
        }else {
            order.setGrouponPrice(grouponRules.getDiscount());
        }
        BigDecimal orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        order.setOrderPrice(orderPrice);
        order.setActualPrice(orderPrice.subtract(integralPrice));
        order.setUpdateTime(LocalDateTime.now());
        order.setAddTime(LocalDateTime.now());
        order.setDeleted(false);
        // 加入到order表
        orderMapper.insertSelective(order);

        // 获取次orderId
        Integer orderId = order.getId();

        // 获取此订单包含的货品列表
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.or().andDeletedEqualTo(false).andCheckedEqualTo(true).andUserIdEqualTo(userId);
        List<MarketCart> checkedGoodsList = cartMapper.selectByExample(marketCartExample);

        // 记录cartId，之后修改cart表
        List<Integer> cartIdList = new ArrayList<>();
        int row2 = 0;
        for (MarketCart marketCart : checkedGoodsList) {

            MarketOrderGoods orderGoods = new MarketOrderGoods();
            orderGoods.setOrderId(orderId);
            Integer goodsId = marketCart.getGoodsId();
            orderGoods.setGoodsId(goodsId);
            orderGoods.setGoodsName(marketCart.getGoodsName());
            orderGoods.setGoodsSn(marketCart.getGoodsSn());
            orderGoods.setProductId(marketCart.getProductId());
            orderGoods.setNumber(marketCart.getNumber());
            // 获取此商品的信息
            MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
            orderGoods.setPrice(goods.getRetailPrice());
            orderGoods.setSpecifications(marketCart.getSpecifications());
            orderGoods.setPicUrl(marketCart.getPicUrl());
            orderGoods.setComment(0);
            orderGoods.setAddTime(LocalDateTime.now());
            orderGoods.setUpdateTime(LocalDateTime.now());
            orderGoods.setDeleted(false);
            // 添加orderGoods表
            orderGoodsMapper.insertSelective(orderGoods);

            cartIdList.add(marketCart.getId());
        }
        MarketCart marketCart = new MarketCart();
        marketCart.setUpdateTime(LocalDateTime.now());
        marketCart.setDeleted(true);
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andIdIn(cartIdList);
        cartMapper.updateByExampleSelective(marketCart, cartExample);

        return orderId;

    }

    @Override
    public Integer prepayOrder(Integer orderId) {
        // 修改订单状态
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        order.setOrderStatus(MarketConstant.HAVE_PAYMENT);
        order.setUpdateTime(LocalDateTime.now());
        order.setPayId(getOrderSn());
        order.setPayTime(LocalDateTime.now());
        int row = orderMapper.updateByPrimaryKeySelective(order);

        return row;
    }

    /**
     * @MethodName getOrderSn
     * @Description   获取一个随机的6位数
     * @return: java.lang.String
     * @Author MZ
     * @Date 16:55 2023/5/22
     **/
    private static String getOrderSn() {
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ISO_LOCAL_DATE);
        String replace = format.replace("-", "");
        Random random = new Random();
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }

        return replace + str;
    }


}
